// 小程序开发api接口工具包，https://github.com/gooking/wxapi
const CONFIG = require('./config.js')
const API_BASE_URL = 'https://api.it120.cc'

var subDomain = '-';
var merchantId = '0';

const request = (url, needSubDomain, method, data) => {
  let _url = API_BASE_URL + (needSubDomain ? '/' + CONFIG.subDomain : '') + url
  return new Promise((resolve, reject) => {
    wx.request({
      url: _url,
      method: method,
      data: data,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success(request) {
        resolve(request.data)
      },
      fail(error) {
        reject(error)
      },
      complete(aaa) {
        // 加载完成
      }
    })
  })
}

/**
 * 小程序的promise没有finally方法，自己扩展下
 */
Promise.prototype.finally = function (callback) {
  var Promise = this.constructor;
  return this.then(
    function (value) {
      Promise.resolve(callback()).then(
        function () {
          return value;
        }
      );
    },
    function (reason) {
      Promise.resolve(callback()).then(
        function () {
          throw reason;
        }
      );
    }
  );
}

module.exports = {
  request,
  queryMobileLocation: (data) => {
    return request('/common/mobile-segment/location', false, 'get', data)
  },

  fetchShopsCities: function fetchShopsCities() {
    return request('/shop/subshop/cities', true, 'get');
  },
  fetchShops: function fetchShops(data) {
    return request('/shop/subshop/list', true, 'post', data);
  },
  queryConfigBatch: (keys) => {
    return request('/config/values', true, 'get', { keys })
  },
  scoreRules: (data) => {
    return request('/score/send/rule', true, 'post', data)
  },
  scoreSign: (token) => {
    return request('/score/sign', true, 'post', {
      token
    })
  },
  scoreSignLogs: (data) => {
    return request('/score/sign/logs', true, 'post', data)
  },
  scoreTodaySignedInfo: (token) => {
    return request('/score/today-signed', true, 'get', {
      token
    })
  },
  scoreExchange: (number, token) => {
    return request('/score/exchange', true, 'post', {
      number,
      token
    })
  },
  scoreLogs: (data) => {
    return request('/score/logs', true, 'post', data)
  },
  shareGroupGetScore: (referrer, encryptedData, iv) => {
    return request('/score/share/wxa/group', true, 'post', {
      referrer,
      encryptedData,
      iv
    })
  },
  kanjiaList: (data) => {
    return request('/shop/goods/kanjia/list', true, 'post', data)
  },
  kanjiaSet: (goodsId) => {
    return request('/shop/goods/kanjia/set', true, 'get', { goodsId })
  },
  kanjiaJoin: (kjid, token) => {
    return request('/shop/goods/kanjia/join', true, 'post', {
      kjid,
      token
    })
  },
  kanjiaDetail: (kjid, joiner) => {
    return request('/shop/goods/kanjia/info', true, 'get', {
      kjid,
      joiner
    })
  },
  kanjiaHelp: (kjid, joiner, token, remark) => {
    return request('/shop/goods/kanjia/help', true, 'post', {
      kjid,
      joinerUser: joiner,
      token,
      remark
    })
  },
  kanjiaHelpDetail: (kjid, joiner, token) => {
    return request('/shop/goods/kanjia/myHelp', true, 'get', {
      kjid,
      joinerUser: joiner,
      token
    })
  },
  checkToken: (token) => {
    return request('/user/check-token', true, 'get', {
      token
    })
  },
  addTempleMsgFormid: (data) => {
    return request('/template-msg/wxa/formId', true, 'post', data)
  },
  sendTempleMsg: (data) => {
    return request('/template-msg/put', true, 'post', data)
  },
  wxpay: (data) => {
    return request('/pay/wx/wxapp', true, 'post', data)
  },
  alipay: (data) => {
    return request('/pay/alipay/semiAutomatic/payurl', true, 'post', data)
  },
  login: (code) => {
    return request('/user/wxapp/login', true, 'post', {
      code,
      type: 2
    })
  },
  register: (data) => {
    return request('/user/wxapp/register/complex', true, 'post', data)
  },
  banners: (data) => {
    return request('/banner/list', true, 'get', data)
  },
  goodsCategory: () => {
    return request('/shop/goods/category/all', true, 'get')
  },
  goods: (data) => {
    return request('/shop/goods/list', true, 'post', data)
  },
  goodsDetail: (id) => {
    return request('/shop/goods/detail', true, 'get', {
      id
    })
  },
  goodsPrice: (data) => {
    return request('/shop/goods/price', true, 'post', data)
  },
  goodsReputation: (data) => {
    return request('/shop/goods/reputation', true, 'post', data)
  },
  coupons: (data) => {
    return request('/discounts/coupons', true, 'get', data)
  },
  couponDetail: (id) => {
    return request('/discounts/detail', true, 'get', {
      id
    })
  },
  myCoupons: (data) => {
    return request('/discounts/my', true, 'get', data)
  },
  fetchCoupons: (data) => {
    return request('/discounts/fetch', true, 'post', data)
  },
  noticeList: (data) => {
    return request('/notice/list', true, 'post', data)
  },
  noticeDetail: (id) => {
    return request('/notice/detail', true, 'get', {
      id
    })
  },
  addAddress: (data) => {
    return request('/user/shipping-address/add', true, 'post', data)
  },
  updateAddress: (data) => {
    return request('/user/shipping-address/update', true, 'post', data)
  },
  deleteAddress: (id, token) => {
    return request('/user/shipping-address/delete', true, 'post', {
      id,
      token
    })
  },
  queryAddress: (token) => {
    return request('/user/shipping-address/list', true, 'get', {
      token
    })
  },
  defaultAddress: (token) => {
    return request('/user/shipping-address/default', true, 'get', {
      token
    })
  },
  addressDetail: (id, token) => {
    return request('/user/shipping-address/detail', true, 'get', {
      id,
      token
    })
  },
  pingtuanSet: (goodsId) => {
    return request('/shop/goods/pingtuan/set', true, 'get', {
      goodsId
    })
  },
  pingtuanOpen: (goodsId, token) => {
    return request('/shop/goods/pingtuan/open', true, 'post', {
      goodsId,
      token
    })
  },
  myjoinlist: (tuanId, token) => {
    return request('/shop/goods/pingtuan/my-join-list', true, 'post', {
      tuanId,
      token
    })
  },
  tuanInfo: (tuanId, token) => {
    return request('/shop/goods/pingtuan/tuanInfo', true, 'get', {
      tuanId,
      token
    })
  },
  pingtuanList: (goodsId) => {
    return request('/shop/goods/pingtuan/list', true, 'get', {
      goodsId
    })
  },
  videoDetail: (videoId) => {
    return request('/media/video/detail', true, 'get', {
      videoId
    })
  },
  bindMobile: (data) => {
    return request('/user/wxapp/bindMobile', true, 'post', data)
  },
  userDetail: (token) => {
    return request('/user/detail', true, 'get', {
      token
    })
  },
  userAmount: (token) => {
    return request('/user/amount', true, 'get', {
      token
    })
  },
  orderCreate: (data) => {
    return request('/order/create', true, 'post', data)
  },
  orderList: (data) => {
    return request('/order/list', true, 'post', data)
  },
  orderDetail: (id, token) => {
    return request('/order/detail', true, 'get', {
      id,
      token
    })
  },
  orderDelivery: (orderId, token) => {
    return request('/order/delivery', true, 'post', {
      orderId,
      token
    })
  },
  orderReputation: (data) => {
    return request('/order/reputation', true, 'post', data)
  },
  orderClose: (orderId, token) => {
    return request('/order/close', true, 'post', {
      orderId,
      token
    })
  },
  orderPay: (orderId, token) => {
    return request('/order/pay', true, 'post', {
      orderId,
      token
    })
  },
  orderStatistics: (token) => {
    return request('/order/statistics', true, 'get', {
      token
    })
  },
  withDrawApply: (money, token) => {
    return request('/user/withDraw/apply', true, 'post', {
      money,
      token
    })
  },
  withDrawDetail: (token, id) => {
    return request('/user/withDraw/detail', true, 'get', {
      token,
      id
    })
  },
  withDrawLogs: (data) => {
    return request('/user/withDraw/list', true, 'post', data)
  },
  province: () => {
    return request('/common/region/v2/province', false, 'get')
  },
  nextRegion: (pid) => {
    return request('/common/region/v2/child', false, 'get', {
      pid
    })
  },
  cashLogs: (data) => {
    return request('/user/cashLog', true, 'post', data)
  },
  rechargeSendRules: () => {
    return request('/user/recharge/send/rule', true, 'get')
  },
  payBillDiscounts: () => {
    return request('/payBill/discounts', true, 'get')
  },
  payBill: (data) => {
    return request('/payBill/pay', true, 'post', data)
  },
  vipLevel: () => {
    return request('/config/vipLevel', true, 'get')
  },
  fxApply: (token, name, mobile) => {
    return request('/saleDistribution/apply', true, 'post', { token, name, mobile })
  },
  fxApplyProgress: (token) => {
    return request('/saleDistribution/apply/progress', true, 'get', { token })
  },
  fxMembers: (data) => {
    return request('/saleDistribution/members', true, 'post', data)
  },
  fxCommisionLog: (data) => {
    return request('/saleDistribution/commision/log', true, 'post', data)
  },
  wxaQrcode: (data) => {
    return request('/qrcode/wxa/unlimit', true, 'post', data)
  },
  uploadFile: (token, tempFilePath) => {
    const uploadUrl = API_BASE_URL + '/' + CONFIG.subDomain + '/dfs/upload/file'
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: uploadUrl,
        filePath: tempFilePath,
        name: 'upfile',
        formData: {
          'token': token
        },
        success(res) {
          resolve(JSON.parse(res.data))
        },
        fail(error) {
          reject(error)
        },
        complete(aaa) {
          // 加载完成
        }
      })
    })
  },
  refundApply: (token, orderId, type, logisticsStatus, reason, amount, remark, pic) => {
    return request('/order/refundApply/apply', true, 'post', {
      token,
      orderId,
      type,
      logisticsStatus,
      reason,
      amount,
      remark,
      pic
    })
  },
  refundApplyDetail: (token, orderId) => {
    return request('/order/refundApply/info', true, 'get', {
      token,
      orderId
    })
  },
  refundApplyCancel: (token, orderId) => {
    return request('/order/refundApply/cancel', true, 'post', {
      token,
      orderId
    })
  },
  cmsCategories: () => {
    return request('/cms/category/list', true, 'get', {})
  },
  cmsArticles: (data) => {
    return request('/cms/news/list', true, 'post', data)
  },
  cmsArticleDetail: (id) => {
    return request('/cms/news/detail', true, 'get', {
      id
    })
  },
  invoiceList: (data) => {
    return request('/invoice/list', true, 'post', data)
  },
  invoiceApply: (data) => {
    return request('/invoice/apply', true, 'post', data)
  },
  invoiceDetail: (token, id) => {
    return request('/invoice/info', true, 'get', { token, id })
  },
  depositList: (data) => {
    return request('/deposit/list', true, 'post', data)
  },
  payDeposit: (data) => {
    return request('/deposit/pay', true, 'post', data)
  },
  depositInfo: (token, id) => {
    return request('/deposit/info', true, 'get', { token, id })
  },
  depositBackApply: (token, id) => {
    return request('/deposit/back/apply', true, 'post', { token, id })
  }

  





  ,
  fap: (key) => {
    return request('/cms/page/info', true, 'get', {key})
  }
  ,
  wxinfo: (token) => {
    return request('/user/wxinfo', true, 'get', {token})
  },
  templateMessage: (data) => {
    return request('https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN', true, 'post', data)
  },

  jicunGoodsList: data => {
    return request('/user/jicunGoods/list', 'post', data)
},






wxappServiceLogin: function wxappServiceLogin(data) {
  return request('/user/wxappService/login', true, 'post', data);
},
wxappServiceLoginWxaMobile: function wxappServiceLoginWxaMobile(data) {
  return request('/user/wxappService/login/mobile', true, 'post', data);
},

login_wx: function login_wx(code) {
  return request('/user/wxapp/login', true, 'post', {
    code: code,
    type: 2
  });
},
login_q: function login_q(code) {
  return request('/user/q/login', true, 'post', {
    code: code,
    type: 2
  });
},
loginWxaMobile: function loginWxaMobile(code, encryptedData, iv) {
  return request('/user/wxapp/login/mobile', true, 'post', {
    code: code,
    encryptedData: encryptedData,
    iv: iv
  });
},
loginWxaMobileV2: function loginWxaMobileV2(data) {
  return request('/user/wxapp/login/mobile', true, 'post', data);
},
login_username: function login_username(data) {
  return request('/user/username/login', true, 'post', data);
},
bindUsername: function bindUsername(token, username) {
  var pwd = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';

  return request('/user/username/bindUsername', true, 'post', {
    token: token, username: username, pwd: pwd
  });
},
login_mobile: function login_mobile(mobile, pwd) {
  var deviceId = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
  var deviceName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';

  return request('/user/m/login', true, 'post', {
    mobile: mobile, pwd: pwd, deviceId: deviceId, deviceName: deviceName
  });
},
loginMobileSmsCode: function loginMobileSmsCode(data) {
  return request('/user/m/loginMobile', true, 'post', data);
},
resetPwdUseMobileCode: function resetPwdUseMobileCode(mobile, pwd, code) {
  return request('/user/m/reset-pwd', true, 'post', {
    mobile: mobile, pwd: pwd, code: code
  });
},
resetPwdUseEmailCode: function resetPwdUseEmailCode(email, pwd, code) {
  return request('/user/email/reset-pwd', true, 'post', {
    email: email, pwd: pwd, code: code
  });
},
register_complex: function register_complex(data) {
  return request('/user/wxapp/register/complex', true, 'post', data);
},
registerQ: function registerQ(data) {
  return request('/user/q/register', true, 'post', data);
},
register_simple: function register_simple(data) {
  return request('/user/wxapp/register/simple', true, 'post', data);
},
authorize: function authorize(data) {
  return request('/user/wxapp/authorize', true, 'post', data);
},
register_username: function register_username(data) {
  return request('/user/username/register', true, 'post', data);
},
register_mobile: function register_mobile(data) {
  return request('/user/m/register', true, 'post', data);
},


modifyUserInfo: function modifyUserInfo(data) {
  return request('/user/modify', true, 'post', data);
},
bindSeller: function bindSeller(data) {
  return request('/user/bindSeller', true, 'post', data);
},

wxappServiceLogin: function wxappServiceLogin(data) {
  return request('/user/wxappService/login', true, 'post', data);
},
wxappServiceLoginWxaMobile: function wxappServiceLoginWxaMobile(data) {
  return request('/user/wxappService/login/mobile', true, 'post', data);
},
wxappServiceRegisterComplex: function wxappServiceRegisterComplex(data) {
  return request('/user/wxappService/register/complex', true, 'post', data);
},
wxappServiceRegisterSimple: function wxappServiceRegisterSimple(data) {
  return request('/user/wxappService/register/simple', true, 'post', data);
},
wxappServiceAuthorize: function wxappServiceAuthorize(data) {
  return request('/user/wxappService/authorize', true, 'post', data);
},
wxappServiceBindMobile: function wxappServiceBindMobile(data) {
  return request('/user/wxappService/bindMobile', true, 'post', data);
},
wxappServiceBindOpenid: function wxappServiceBindOpenid(data) {
  return request('/user/wxappService/bindOpenid', true, 'post', data);
},
wxappServiceEncryptedData: function wxappServiceEncryptedData(data) {
  return request('/user/wxappService/decode/encryptedData', true, 'post', data);
},


init2: function init2(a, b) {
  API_BASE_URL = a;
  subDomain = b;
},
init: function init(b) {
  subDomain = b;
},
setMerchantId: function setMerchantId(mchid) {
  merchantId = mchid;
},
init3: function init3(_ref) {
  var _ref$apiBaseUrl = _ref.apiBaseUrl,
      apiBaseUrl = _ref$apiBaseUrl === undefined ? API_BASE_URL : _ref$apiBaseUrl,
      subD = _ref.subDomain,
      req = _ref.request;

  // 某些需求需要定制化 request，需要保证传入自定义 reuqest 与默认 request 参数一致
  if (req) {
    request = req;
  }
  API_BASE_URL = apiBaseUrl;
  subDomain = subD;
},



shortUrl: function shortUrl() {
  var url = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';

  return request('/user/wxa/urlGenerate/link', false, 'post', { url: url });
},

shortUrl: function shortUrl(data) {
  return request('/user/wxa/urlGenerate/link', true, 'post', data);
},

}